<template>
    <div class="equity-manage-main">
        <ZwTable
            ref="tableRef"
            class="table-box"
            :show-pagination="false"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-data-format="fetchDataFormat"
            :param-prop="state.paramProp"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperateLeft>
                <div class="left">
                    <div class="title-label">
                        <div class="title-label-text">默认权益</div>
                    </div>
                    <div class="title-desc">默认权益的服务方式为系统核销，根据在会员权益中的设置规则自动执行。</div>
                </div>
            </template>
        </ZwTable>
        <ZwTable
            ref="tableRef2"
            class="table-box"
            :show-pagination="false"
            :option="tableOption"
            :row-key="getRowKey"
            :param-prop="state.paramProp"
            :fetch-data-format="fetchDataFormat2"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperateLeft>
                <div class="left table-title">
                    <div class="title-label">
                        <div class="title-label-text">自定义权益</div>
                    </div>
                    <div class="title-desc">自定义权益的服务方式为线下核销，需商家配合执行。</div>
                    <div class="title-button">
                        <el-button v-auth="'ADD_EQUITY'" type="primary" @click="handlerAddEquity"> 添加权益 </el-button>
                    </div>
                </div>
            </template>
        </ZwTable>
        <DialogEquity ref="dialogEquityRef" @dialogEquitySubmit="initData" />
    </div>
</template>
<script setup lang="tsx">
import { ref, reactive } from 'vue';
import { deepCopy } from '@/utils/helper';
import { ElMessage, ElButton, ElImage, ElIcon, ElTooltip, ElPopconfirm } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import ZwTable from '@/components/zw/table/Table';
import DialogEquity from './components/dialogEquity.vue';
import { getMemberPriorityList, delMemberPriority } from '@/api/member/equityManage/index';

const tableRef = ref<any>(null);
const tableRef2 = ref<any>(null);
const dialogEquityRef = ref<any>(null);

const defaultIconUrl = location.origin + '/static/member/default_rights_icon.png';

const tableOption = [
    {
        prop: 'priority_inner_name',
        label: '权益名称'
    },
    {
        prop: 'priority_outer_name',
        label: '展示名称'
    },
    {
        prop: 'priority_icon',
        label: '权益图标',
        render({ row }: any) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            const slotDefaultError = () => (
                <div class="image_slot">
                    {row.priority_inner_name == '多倍积分' ? (
                        <img src="/static/member/points.png" class="icon_img" />
                    ) : (
                        <img src="/static/member/free_shipping.png" class="icon_img" />
                    )}
                </div>
            );
            return (
                <div class="equity-manage-table">
                    {/* <ElImage vSlots={{ error: slotError }} src={row.priority_icon} fit="cover" class="icon_img"></ElImage> */}
                    {row.default == 1 ? (
                        <ElImage
                            vSlots={{ error: slotDefaultError }}
                            src={row.priority_icon}
                            fit="cover"
                            class="icon_img"></ElImage>
                    ) : (
                        <ElImage
                            vSlots={{ error: slotError }}
                            src={row.priority_icon}
                            fit="cover"
                            class="icon_img"></ElImage>
                    )}
                </div>
            );
        }
    },
    {
        prop: 'priority_brief',
        label: '权益简介',
        showOverflowTooltip: true
    },
    {
        prop: 'priority_status',
        label: '权益状态',
        render({ row }: any) {
            return (
                <div class="equity-manage-table">
                    <div class={`status ${row.priority && row.priority.length ? 'status_green' : ''}`}>
                        {row.priority && row.priority.length ? '已使用' : '未使用'}
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 270,
        isOperate: true,
        render({ row, column, index }: any) {
            const defaultButton = () => (
                <el-button class="table-btn" vAuth={'DEL'} size="small" disabled={row.priority?.length > 0}>
                    删除
                </el-button>
            );
            return (
                <div class="zw-table__btn-box">
                    <ElButton size="small" vAuth={'EDIT'} onClick={() => handlerEdit(row)}>
                        编辑
                    </ElButton>
                    {row.default != 1 && (
                        <span>
                            <ElTooltip
                                class="box_item"
                                effect="dark"
                                placement="top"
                                content={onTooltip(row)}
                                disabled={!row.priority?.length}>
                                <span>
                                    <ElPopconfirm
                                        placement="top"
                                        title="确定删除此权益吗?"
                                        vSlots={{ reference: defaultButton }}
                                        onConfirm={() => handlerDel(row)}></ElPopconfirm>
                                </span>
                            </ElTooltip>
                        </span>
                    )}
                </div>
            );
        }
    }
];

const defaultParams = {
    keyword: '',
    gradeId: '',
    date: [],
    page_size: 999
};

const state = reactive({
    searchParams: deepCopy(defaultParams),
    paramProp: { page: 'page', pageSize: 'page_size' }
});

const getRowKey = (row: any) => {
    return row.id;
};

const fetchDataFormat = (list: any) => {
    return list.filter((el: any) => el.default === 1);
};

const fetchDataFormat2 = (list: any) => {
    return list.filter((el: any) => el.default != 1);
};

const fetchApi = () => {
    return getMemberPriorityList;
};

const onTooltip = (row: any) => {
    let str = '';
    if (row.priority.length > 0) {
        row.priority.forEach((item: any) => {
            str += `${item?.member_level_name}、`;
        });
        str = str.substring(0, str.length - 1);
    }
    return `${str}正在使用此权益不可删除`;
};

const handlerAddEquity = () => {
    dialogEquityRef.value.form.corpId = '';
    dialogEquityRef.value.form.id = '';
    dialogEquityRef.value.form.priority_outer_name = '';
    dialogEquityRef.value.form.priority_inner_name = '';
    dialogEquityRef.value.form.priority_icon = defaultIconUrl;
    dialogEquityRef.value.form.priority_brief = '';
    dialogEquityRef.value.form.default = 2;
    dialogEquityRef.value.form.appType = 1;
    dialogEquityRef.value.appDialog.title = '添加权益';
    dialogEquityRef.value.appDialog.visible = true;
};

const handlerEdit = (val?: any) => {
    Object.assign(dialogEquityRef.value.form, val);
    dialogEquityRef.value.appDialog.title = '编辑权益';
    dialogEquityRef.value.appDialog.visible = true;
};

const handlerDel = async (val?: any) => {
    const params = {
        id: val.id
    };
    const res = await delMemberPriority(params);
    ElMessage.success('删除成功');
    tableRef2.value.reload();
    //
};

const initData = () => {
    tableRef.value.reload();
    tableRef2.value.reload();
};
</script>
<style lang="scss" scoped>
.equity-manage-main {
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;

    .table-title {
        margin-top: 37px;
    }

    .title-label {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        &::before {
            display: inline-block;
            width: 4px;
            height: 16px;
            content: '';
            background: #ff6b00;
        }

        .title-label-text {
            margin-right: 9px;
            margin-left: 6px;
            color: #33302d;
            font-size: 16px;
            font-weight: 500;
        }
    }

    .title-desc {
        margin-left: 10px;
        color: #969696;
        font-size: 14px;
        line-height: 14px;
    }

    .title-button {
        margin: 10px 0 0;
    }

    :deep(.equity-manage-table) {
        .icon_img {
            width: 24px;
            height: 24px;
            border-radius: 50%;

            .icon_error {
                font-size: 24px;
            }
        }

        .status {
            display: flex;
            align-items: center;

            &::before {
                display: inline-block;
                width: 8px;
                height: 8px;
                margin-right: 6px;
                content: '';
                border-radius: 4px;
                background: #ccc;
            }
        }

        .status_green::before {
            background: #32d1ad;
        }
    }
}
</style>
